import { Injectable } from '@angular/core'
import { Observable, throwError, of } from 'rxjs'
import { PUBLIC_URL, COMB_URL } from 'app/utils/contraints'
import { generateOptions } from 'app/utils/helpers'
import { HttpClient } from '@angular/common/http'
import { map, catchError } from 'rxjs/operators'
import { IExchangeRateQueryParams, IExchangeRate } from '@shared/interfaces/common'
import { ExchangeRate } from '@shared/interfaces/acquirer'
import { TitleService } from '@delon/theme'
import { ISearchOption } from '@shared/interfaces/search'
import { I18NService } from '@core'
import { ETradeChannel } from '@shared/enums'
import { ETaskTypeMap, ETaskStatusMap } from '@shared/interfaces/task'
import { EHoldReason, EReleaseReason, ERiskStatusMap } from '@shared/interfaces/operation'
import { ReportTypeMap } from '@shared/interfaces/report'
import { ETermVendar } from '@shared/interfaces/terminal'
import { NzMessageService } from 'ng-zorro-antd'

@Injectable({
  providedIn: 'root',
})
export class PublicService {
  constructor(
    public titleService: TitleService,
    private http: HttpClient,
    private i18n: I18NService,
    private msg: NzMessageService,
  ) {}

  getExchangeRate(params: IExchangeRateQueryParams): Observable<IExchangeRate[]> {
    const url = `${COMB_URL}/camel/public/exchangerate`
    if (!params.dstCurrency || !params.srcCurrency) {
      return of([])
    }
    const options = generateOptions(params)

    return this.http.get<IExchangeRate[]>(url, options).pipe(
      catchError(err => {
        const { status } = err
        console.log('status', status)
        if (status === 404) {
          this.msg.error('不支持的转换关系')
        }
        return of([])
      }),
    )
  }

  setTitle(title: string): void {
    this.titleService.setTitle(title)
  }

  /**
   * @param e: key 为 对应 Option 的值，value 为i18n形式，翻译后作为label
   */
  genOptions(
    e:
      | typeof ETradeChannel
      | typeof EHoldReason
      | typeof EReleaseReason
      | typeof ETaskTypeMap
      | typeof ETaskStatusMap
      | typeof ERiskStatusMap
      | typeof ReportTypeMap
      | typeof ETermVendar,
  ): ISearchOption[] {
    return Object.keys(e).map(key => ({
      label: this.trans(e[key]),
      value: key,
    }))
  }

  trans(str: string): string {
    return this.i18n.fanyi(str)
  }
}
